package com.example.tibetanmedicinechest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.tibetanmedicinechest.mapper.CaseMapper;
import com.example.tibetanmedicinechest.model.Case;
import com.example.tibetanmedicinechest.model.Favorite;
import com.example.tibetanmedicinechest.mapper.FavoriteMapper;
import com.example.tibetanmedicinechest.service.IFavoriteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 编程笨蛋
 * @since 2023-08-12
 */
@Service
public class FavoriteServiceImpl extends ServiceImpl<FavoriteMapper, Favorite> implements IFavoriteService {

    @Autowired
    FavoriteMapper favoriteMapper;
    @Autowired
    CaseMapper caseMapper;
    @Override
    @Transactional
    public boolean addFavorite(int id) {
        Favorite fa = new Favorite();
        fa.setCase_id(id);
        fa.setUser_id(1);
        int insert = favoriteMapper.insert(fa);
        return insert==1;
    }

    @Override
    @Transactional
    public boolean deleteFavorite(int id) {
        LambdaQueryWrapper<Favorite> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Favorite::getCase_id,id);
        int delete = favoriteMapper.delete(lqw);
        return delete==1;
    }

    @Override
    public List<Map<String, Object>> selectFavoriteById(int id) {
        List<Map<String, Object>> datas = new ArrayList<>();
        LambdaQueryWrapper<Favorite> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(Favorite::getUser_id,id);
        List<Map<String, Object>> favorites = favoriteMapper.selectFavoriteById(id);
        System.out.println(favorites);
        if(favorites.size()!=0)
        {
            for (Map<String, Object> favorite:favorites) {
                System.out.println(favorite + "1");
                Map<String,Object> data = new HashMap<>();
                Case aCase = caseMapper.selectById((Serializable) favorite.get("case_id"));
                data.put("id",aCase.getId());
                data.put("images",aCase.getImage());
                data.put("name",aCase.getName());
                data.put("introduce",aCase.getIntroduce());
                datas.add(data);
            }
        }
        return datas;
    }

}
